package com.kcyu.egoodsmapbackend.controller;

import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kcyu.egoodsmapbackend.entity.Category;
import com.kcyu.egoodsmapbackend.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author kcyu
 * @since 2025-02-28
 */
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private ICategoryService categoryService;

    @PostMapping("/saveOrUpdate")
    public SaResult saveOrUpdate(@RequestBody Category category) {
        // 判断是否新增
        if (category.getId() == null) {
            // 计算排序
            QueryWrapper<Category> wrapper = new QueryWrapper<Category>();
            if(category.getLevel() == 0) {
                wrapper.lambda().eq(Category::getLevel, 0);
                wrapper.lambda().orderByDesc(Category::getSort);
                wrapper.lambda().last("limit 1");
            } else {
                wrapper.lambda().eq(Category::getParentId, category.getParentId());
                wrapper.lambda().orderByDesc(Category::getSort);
                wrapper.lambda().last("limit 1");
            }

            int maxSort = categoryService.getBaseMapper().selectOne(wrapper).getSort();
            category.setSort(maxSort + 1);
        }
        categoryService.saveOrUpdate(category);
        return SaResult.ok("新增成功");
    }

    @GetMapping("/getFirstLevelCategory")
    public SaResult getFirstLevelCategory() {
        return SaResult.ok().setData(categoryService.getFirstLevelCategory());
    }

    @GetMapping("/getSecondLevelCategory")
    public SaResult getSecondLevelCategory(@RequestParam("parentId") String parentId) {
        return SaResult.ok().setData(categoryService.getBaseMapper().selectList(
                new QueryWrapper<Category>().eq("parent_id", parentId).orderByAsc("sort"))
        );
    }

    @PostMapping("/saveSorts")
    public SaResult saveSorts(@RequestBody List<Category> categories) {
        // 遍历传入的分类列表，仅更新 sort 属性
        for (Category category : categories) {
            Category existingCategory = categoryService.getById(category.getId());
            if (existingCategory != null) {
                existingCategory.setSort(category.getSort()); // 仅更新 sort 属性
                categoryService.updateById(existingCategory); // 单条更新
            }
        }
        return SaResult.ok("保存成功");
    }


    @GetMapping("/getOne")
    public SaResult getOne(@RequestParam("id") String id) {
        return SaResult.ok().setData(categoryService.getById(id));
    }

}
